package com.xjnt.frameworks.plugin.shiro;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.util.WebUtils;

import com.google.common.collect.Lists;
import com.xjnt.frameworks.plugin.shiro.handler.AuthzHandler;
import com.xjnt.frameworks.plugin.shiro.jdbc.AuthzJdbcLoader;

/**
 * ShiroKit. (Singleton, ThreadSafe)
 */
public class ShiroKit {

	/**
	 * Session中保存的请求的Key值
	 */
	private static String SAVED_REQUEST_KEY = "ShiroSavedRequest";

	/**
	 * 用来记录那个action或者actionpath中是否有shiro认证注解。
	 */
	private static ConcurrentMap<String, AuthzHandler> authzMaps = null;

	/**
	 * 用来记录那个action或者actionpath中是否有shiro认证注解。
	 */
	private static Map<String, AuthzHandler> authzJdbcMaps = null;

	/**
	 * jdbc的权限加载器
	 */
	private static AuthzJdbcLoader authzJdbcLoader;

	public static AntPathMatcher antPathMatcher = new AntPathMatcher();

	private static boolean AND = false;

	/**
	 * 禁止初始化
	 */
	private ShiroKit() {
	}

	static void init(ConcurrentMap<String, AuthzHandler> maps, AuthzJdbcLoader authzJdbcService, boolean isAND) {
		authzMaps = maps;
		authzJdbcLoader = authzJdbcService;
		AND = isAND;
		loadJdbcAuthz(false);
	}

	public static AuthzHandler getAuthzHandler(String actionKey) {
		/*
		 * if(authzMaps.containsKey(controllerClassName)){ return true; }
		 */
		return authzMaps.get(actionKey);
	}

	static List<AuthzHandler> getJdbcAuthzHandler(HttpServletRequest request) {
		List<AuthzHandler> result = Lists.newArrayList();
		String url = WebUtils.getPathWithinApplication(request);
		for (String key : authzJdbcMaps.keySet()) {
			if (antPathMatcher.match(key, url)) {
				result.add(authzJdbcMaps.get(key));
				if (!AND)
					break;
			}
		}
		return result;
	}

	public static List<AuthzHandler> getAuthzHandler(HttpServletRequest request, String actionKey) {
		List<AuthzHandler> result = getJdbcAuthzHandler(request);
		AuthzHandler ah = getAuthzHandler(actionKey);
		if (ah != null) {
			result.add(ah);
		}
		return result;
	}

	/**
	 * Session中保存的请求的Key值
	 * 
	 * @return
	 */
	public static final String getSavedRequestKey() {
		return SAVED_REQUEST_KEY;
	}

	/**
	 * 清除后重新加载
	 * 
	 * @param clear
	 */
	public static void loadJdbcAuthz(boolean clear) {
		if (authzJdbcMaps != null) {
			if (clear) {
				authzJdbcMaps.clear();
			}
		}
		authzJdbcMaps = authzJdbcLoader.getJdbcAuthz();
	}
}
